package com.yurun.orgstudentmodule.service.Impl;

import com.yurun.commonapi.api.CommonResult;
import com.yurun.commonapi.aspect.PermissionAnnotation;
import com.yurun.commonapi.dto.StudentSignListDTO;
import com.yurun.commonapi.pojo.*;
import com.yurun.commonapi.vo.StudentSignListVO;
import com.yurun.orgstudentmodule.mapper.AloneClassMonthPlanAndSummaryMapper;
import com.yurun.orgstudentmodule.mapper.StudentDocumentMapper;
import com.yurun.orgstudentmodule.service.StudentInfoService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigInteger;
import java.util.*;

@Service
@Transactional
public class StudentInfoImpl implements StudentInfoService {
//    private static Logger logger = Logger.getLogger(StudentInfoImpl.class);
    @Autowired
    private StudentDocumentMapper studentDocumentMapper;

    @Autowired
    private AloneClassMonthPlanAndSummaryMapper aloneClassMonthPlanAndSummaryMapper;


    @Override
    public CommonResult allStudentInfo(int isImport, BigInteger organizationId,BigInteger employeeId, BigInteger branchId, String keyword, int pageNum, int pageSize) {
        /*// 获取用户所有权限id
        List<Integer> resourceId = aloneClassMonthPlanAndSummaryMapper.getResourcesIdByRoleId(aloneClassMonthPlanAndSummaryMapper.getRoleId(employeeId));

        List<String> resource = new ArrayList<>();
        for (int id : resourceId) { // 添加所有权限
            resource.add(aloneClassMonthPlanAndSummaryMapper.getResourcesById(id));
        }
*/
        Map<String, Object> map = new HashMap<>();
        StudentDocument studentDocument = new StudentDocument();
        studentDocument.setOrganizationId(organizationId);
        studentDocument.setBranchId(branchId);
        studentDocument.setStudentName(keyword);
        studentDocument.setIsImport(isImport);
        List<StudentDocument> result = studentDocumentMapper.allStudentInfo(studentDocument);
//        System.out.println(result);
        map.put("total", result.size());
        map.put("data", zljPageHelper(result, pageNum, pageSize));
        return CommonResult.success(map);
        /*List<StudentDocument> list = new ArrayList();
        StudentTrainingTable studentTrainingTable = new StudentTrainingTable();
        studentTrainingTable.setEmployeeId(employeeId);
        studentTrainingTable.setOrganizationId(organizationId);
        studentTrainingTable.setBranchId(branchId);*/
        /*if (keyword.equals("") && branchId.longValue() == 0) { // 机构的所有学生
            List<StudentDocument> result = studentDocumentMapper.getAllStudentInfoByOrgId(organizationId);
            map.put("total", result.size());
            map.put("data", zljPageHelper(result, pageNum, pageSize));
            return CommonResult.success(map);
        } else if (!keyword.equals("") && branchId.longValue() == 0) { // 机构的某个学生
            StudentDocument studentDocument = new StudentDocument();
            studentDocument.setStudentName(keyword);
            studentDocument.setOrganizationId(organizationId);
            List<StudentDocument> result = studentDocumentMapper.getAllStudentInfoByOrgIdAndName(studentDocument);
            map.put("total", result.size());
            map.put("data", zljPageHelper(result, pageNum, pageSize));
            return CommonResult.success(map);
        } else if (keyword.equals("") && branchId.longValue() != 0) { // 分店的所有学生
            StudentDocument studentDocument = new StudentDocument();
            studentDocument.setOrganizationId(organizationId);
            studentDocument.setBranchId(branchId);
            List<StudentDocument> result = studentDocumentMapper.getAllStudentInfoByBranchId(studentDocument);
            map.put("total", result.size());
            map.put("data", zljPageHelper(result, pageNum, pageSize));
            return CommonResult.success(map);
        } else if (!keyword.equals("") && branchId.longValue() != 0) {// 分店的某个学生

            StudentDocument studentDocument = new StudentDocument();
            studentDocument.setStudentName(keyword);
            studentDocument.setOrganizationId(organizationId);
            studentDocument.setBranchId(branchId);
            List<StudentDocument> result = studentDocumentMapper.getAllStudentInfoByBranchIdAndName(studentDocument);
            map.put("total", result.size());
            map.put("data", zljPageHelper(result, pageNum, pageSize));
            return CommonResult.success(map);
        } else if (isImport == 0) {
            StudentDocument studentDocument = new StudentDocument();
            studentDocument.setOrganizationId(organizationId);
            studentDocument.setBranchId(branchId);
            List<StudentDocument> result = studentDocumentMapper.getAllStudentInfoByNoImport(studentDocument);
            map.put("total", result.size());
            map.put("data", zljPageHelper(result, pageNum, pageSize));
            return CommonResult.success(map);
        } else if (isImport == 1) {
            StudentDocument studentDocument = new StudentDocument();
            studentDocument.setOrganizationId(organizationId);
            studentDocument.setBranchId(branchId);
            List<StudentDocument> result = studentDocumentMapper.getAllStudentInfoByImport(studentDocument);
            map.put("total", result.size());
            map.put("data", zljPageHelper(result, pageNum, pageSize));
            return CommonResult.success(map);
        }*/
        /*else if () { // 老师自己的学生
            // 得到自己学生列表
            String studentStr = aloneClassMonthPlanAndSummaryMapper.getStudentByTeacherId(studentTrainingTable);
            // 转换为数组
            String str[] = studentStr.split(",");

            for (String temp : str) {
                studentTrainingTable.setStudentId(BigInteger.valueOf(Long.parseLong(temp)));
                list.add(studentDocumentMapper.getTeacherStudentInfo(BigInteger.valueOf(Long.parseLong(temp))));

            }

            return CommonResult.success(list);
        }*/

        //return CommonResult.failed("暂无数据！");
    }

    @Override
    public CommonResult addStudent(StudentDocument studentDocument) {
        studentDocument.setCreateTime(new Date());
        studentDocument.setUpdateTime(new Date());
        studentDocument.setIsDel(0);
        studentDocument.setIsImport(0); // 未导入
        int flag = studentDocumentMapper.insert(studentDocument);
        if (flag == 1) {
            return CommonResult.success("新增成功！");
        }
        return CommonResult.failed("新增失败！");
    }

    @Override
    public CommonResult getOneStudentInfoByStudentId(StudentDocument studentDocument) {
        return CommonResult.success(studentDocumentMapper.getOneStudentInfoByStudentId(studentDocument));
    }


    //@PermissionAnnotation
    @Override
    public CommonResult editStudent(BigInteger employeeId, StudentDocument studentDocument, int ifAlone) {
        if (studentDocumentMapper.updateByPrimaryKey(studentDocument) == 1) {
            return CommonResult.success("修改成功！");
        }
        return CommonResult.failed("修改失败！");
    }

    //@PermissionAnnotation
    @Override
    @Transactional
    public CommonResult delStudent(BigInteger employeeId, StudentDocument studentDocument, int ifAlone) {
        List<Teacher> list_teacher = studentDocumentMapper.getAllTeacher(studentDocument);
        List<Classroom> list_classroom = studentDocumentMapper.getAllClassroom(studentDocument);
        try {
            for (Teacher temp_teacher : list_teacher) { // 遍历老师
                if (temp_teacher != null) {
                    String str = temp_teacher.getStudentIds();
                    List<String> array = Arrays.asList(str.split(","));
                    for (int i = 0; i < array.size(); i++) { // 遍历老师的学生
                        if (BigInteger.valueOf(Long.parseLong(array.get(i))).equals(studentDocument.getStudentId())) {
                            array.remove(i); // 删除该学生
                        }
                    }
                    Teacher teacher = new Teacher();
                    teacher.setEmployeeId(temp_teacher.getEmployeeId());
                    teacher.setStudentIds(array.toString());
                    teacher.setUpdateTime(new Date());
                    studentDocumentMapper.delTeacherStudentIds(teacher);
                }
            }
            for (Classroom temp_classroom  : list_classroom) { // 遍历班级
                if (temp_classroom != null) {
                    String str = temp_classroom.getStudentIds();
                    List<String> array = Arrays.asList(str.split(","));
                    for (int i = 0; i < array.size(); i++) { // 遍历老师的学生
                        if (BigInteger.valueOf(Long.parseLong(array.get(i))).equals(studentDocument.getStudentId())) {
                            array.remove(i); // 删除该学生
                        }
                    }
                    Classroom classroom = new Classroom();
                    classroom.setClassroomId(temp_classroom.getClassroomId());
                    classroom.setStudentIds(array.toString());
                    classroom.setUpdateTime(new Date());
                    System.out.println(array.toString());
                    studentDocumentMapper.delClassroomStudent(classroom);
                }

            }
            studentDocument.setUpdateTime(new Date());
            studentDocumentMapper.deleteByPrimaryKey(studentDocument);
            return CommonResult.success("删除成功！");
        } catch (Exception e) {
            System.out.println("发生异常,进行手动回滚！");
            // 手动回滚事物
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }

        return CommonResult.failed("删除失败！");
    }

    @Override
    public CommonResult getStudentSignList(StudentSignListVO studentSignListVO) {
        String[] time =studentSignListVO.getSignDates().split(",");
        if (time.length == 2) {
            studentSignListVO.setDate1(time[0]);
            studentSignListVO.setDate2(time[1]);
        }
        List<StudentSignListDTO> list = studentDocumentMapper.getStudentSignList(studentSignListVO);
        Map<String, Object> map = new HashMap<>();
        map.put("total", list.size());
        map.put("data", zljPageHelper1(list, studentSignListVO.getPageNum(), studentSignListVO.getPageSize()));
        return CommonResult.success(map);
    }

    public boolean hasPermission(BigInteger employeeId, BigInteger studentId) {
        // 获取该员工的所有学生
        String studentIds = studentDocumentMapper.getMyStudent(employeeId);
        System.out.println(studentIds);
        for (String temp : studentIds.split(",")) {  // 自己的所有个训学生
            if (studentId.equals(BigInteger.valueOf(Long.parseLong(temp)))) {
                return true;
            }
        }
        // 获取该员工的所有班级
        String classroomIds = studentDocumentMapper.getMyClassroom(employeeId);
        for (String temp : classroomIds.split(",")) {
            // 获取班级表中的studentIds
            String studentIds_class = studentDocumentMapper.getClassroomStudent(BigInteger.valueOf(Long.parseLong(temp)));
            for (String temp1 : studentIds_class.split(",")) {
                if (studentId.equals(BigInteger.valueOf(Long.parseLong(temp1)))) {
                    return true;
                }
            }
        }
        return false;
    }

    public List<StudentDocument> zljPageHelper(List<StudentDocument> list, int pageNum, int pageSize) {
        List<StudentDocument> temp = new ArrayList<>();

        for (int i = pageSize * (pageNum - 1); i < list.size() && i < (pageSize * (pageNum - 1) + pageSize); i++) {
            temp.add(list.get(i));
        }
        return temp;
    }


    public List<StudentSignListDTO> zljPageHelper1(List<StudentSignListDTO> list, int pageNum, int pageSize) {
        List<StudentSignListDTO> temp = new ArrayList<>();

        for (int i = pageSize * (pageNum - 1); i < list.size() && i < (pageSize * (pageNum - 1) + pageSize); i++) {
            temp.add(list.get(i));
        }
        return temp;
    }
}
